import React from 'react';
import { Modal, Form, Input, message, Select } from 'antd';

import { FormInstance } from 'antd/lib/form';
import { MainNumInfo } from '../../../../schema/MainNum';
import { ResourcePoolInfo } from '../../../../schema/ResourcePool';
import { createMainNum } from '../../../../servers/servers';
import { getResourcePoolList } from '../../../../servers/servers';
import { verifyNull } from 'utils/tools';
const { Option } = Select;

/**
 * 主叫号码props
 */
interface IProps {
  callback?: any; //获取暴露方法
}

/**
 * 主叫号码state
 */
interface IState {
  // 当前的操作类型为新增还是编辑
  mode: 'create' | 'modify';
  // 当前操作弹出弹窗的可见性
  visible: boolean;
  resourcePoolList: ResourcePoolInfo[];
}

/**
 * 主叫号码管理操作
 */
export class MainNumPop extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  // 当前的主叫号码信息
  private MainNumInfo?: MainNumInfo;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      mode: 'create',
      visible: false,
      resourcePoolList: [],
    };
  }
  /**
   * 获取列表数据
   */
  private initResourceOptions() {
    getResourcePoolList({
      pageNo: 1,
      pageSize: 10000,
    })
      .then(res => {
        this.setState({
          resourcePoolList: res.data,
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 展开弹窗并设置类型
   */
  public open(mode: 'create' | 'modify'): void {
    this.setState({
      visible: true,
      mode: mode,
    });
    this.initResourceOptions();
  }

  /**
   * 关闭弹窗
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 设置表单值
   */
  public setValue(val: MainNumInfo) {
    setTimeout(() => {
      this.MainNumInfo = val;
      this.formRef.current?.setFieldsValue(val);
    }, 0);
  }

  /**
   * 提交 新增/编辑 的数据
   */
  private submitData(): void {
    const form = this.formRef.current;
    form?.validateFields().then(res => {
      const val = form.getFieldsValue() as MainNumInfo;
      if (this.state.mode === 'create') {
        createMainNum(val)
          .then(res => {
            if (res.code === 0) {
              message.success('创建成功');
              this.close();
              this.props.callback();
            } else {
              message.error(`${res.tips}(错误码: ${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      }
    });
  }

  render() {
    const { visible, mode, resourcePoolList } = this.state;
    if (!visible) {
      return <> </>;
    }

    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };

    return (
      <>
        <Modal
          title={mode === 'create' ? '新建主叫号码' : '编辑主叫号码'}
          width={500}
          visible={visible}
          onOk={() => {
            this.submitData();
          }}
          onCancel={() => {
            this.close();
          }}
        >
          <Form {...layout} layout="horizontal" ref={this.formRef}>
            <Form.Item
              label="主叫号码"
              name="callingNumber"
              validateFirst
              rules={[
                {
                  required: true,
                  message: '请输入主叫号码',
                },
                {
                  message: '只能输入数字',
                  pattern: /^\d+$/,
                },
                {
                  min: 5,
                  message: '请输入5-20位数字',
                },
              ]}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input placeholder="请输入5-20位数字" maxLength={20} />
            </Form.Item>
            <Form.Item label="资源名称" name="resourceId" rules={verifyNull('请选择资源名称')}>
              <Select
                showSearch
                placeholder="请选择"
                allowClear
                getPopupContainer={triggerNode => triggerNode.parentElement}
                optionFilterProp="children"
                filterOption={(input, option) =>
                  (option as any).children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {/* 列表 */}
                {resourcePoolList.map(item => {
                  return (
                    <Option key={item.resourceId} value={item.resourceId}>
                      {item.resourceName}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}
